package com.nebula.service.Impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.enterprise.inject.New;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.nebula.common.Const;
import com.nebula.common.ServerResponse;
import com.nebula.mapper.FilesMapper;
import com.nebula.mapper.FriendsApplicationMapper;
import com.nebula.mapper.FriendsMapper;
import com.nebula.mapper.FriendsSessionMapper;
import com.nebula.mapper.FriendsShareMapper;
import com.nebula.mapper.UserMapper;
import com.nebula.pojo.Files;
import com.nebula.pojo.Friends;
import com.nebula.pojo.FriendsApplication;
import com.nebula.pojo.FriendsApplicationKey;
import com.nebula.pojo.FriendsKey;
import com.nebula.pojo.FriendsSession;
import com.nebula.pojo.FriendsShare;
import com.nebula.pojo.User;
import com.nebula.service.IFriendsService;
import com.nebula.util.FileUtil;
import com.nebula.util.UsernameEncryptionUtil;
import com.nebula.vo.FriendsApplicationVo;
import com.nebula.vo.FriendsSessionVo;
import com.nebula.vo.FriendsShareListVo;
import com.nebula.vo.UserVo;

import oracle.net.aso.f;

@Service("friendsService")
public class FriendsServiceImpl implements IFriendsService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private FriendsMapper friendsMapper;
	@Autowired
	private FriendsApplicationMapper friendsApplicationMapper;
	@Autowired
	private FriendsSessionMapper friendsSessionMapper;
	@Autowired
	private FriendsShareMapper friendsShareMapper;
	@Autowired
	private FilesMapper filesMapper;
	
	public ServerResponse<UserVo> searchFriend(String str,String username){
		User user = userMapper.selectByUsernameOrEmail(str);
		if(user == null){
			return ServerResponse.createByErrorMessage("没有找到你搜索的用户，检查下输入的帐号吧");
		}
		
		int resultCount = friendsMapper.selectFriendByUsernameAndFriendname(username, user.getUsername());

		UserVo userVo = new UserVo();
		userVo.setUsername(user.getUsername());
		userVo.setNickname(user.getNickname());
		userVo.setEncryptionName(UsernameEncryptionUtil.encryptionUsername(user.getUsername()));
		
		if(resultCount > 0){
			return ServerResponse.createBySuccess("（已是好友）",userVo);
		}
		
		return ServerResponse.createBySuccess("",userVo);
	}
	
	/**
	 * @param applicant 申请人
	 * @param respondent 被申请人
	 * @return
	 * @author cx
	 */
	public ServerResponse addFriend(String applicant,String respondent,String message){
		if(applicant.equals(respondent)){
			return ServerResponse.createByErrorMessage("不能添加自己为好友");
		}
		
		FriendsApplication friendsApplication = new FriendsApplication();
		FriendsApplicationKey friendsApplicationKey = new FriendsApplicationKey(applicant, respondent);
		
		friendsApplication.setApplicant(applicant);
		friendsApplication.setRespondent(respondent);
		friendsApplication.setMessages(message);
		friendsApplication.setState(0);
		friendsApplication.setIsview(0);
		
		int resultCount = friendsApplicationMapper.selectByKey(friendsApplicationKey);
		if(resultCount > 0){
			return ServerResponse.createByErrorMessage("您已发送过好友添加请求，请耐心等待");
		}else{
			friendsApplicationKey = new FriendsApplicationKey(respondent, applicant);
			resultCount = friendsApplicationMapper.selectByKey(friendsApplicationKey);
			if(resultCount > 0){
				return ServerResponse.createByErrorMessage("exist");
			}else{
				resultCount = friendsApplicationMapper.insertSelective(friendsApplication);
				if(resultCount > 0){
					return ServerResponse.createBySuccessMessage("您的好友添加请求已经发送成功，等待对方确认");
				}
			}
		}
		return ServerResponse.createByErrorMessage("您的好友添加请求已经发送失败");
	}
	
	public ServerResponse friendsList(String username){
		List<Friends> list = friendsMapper.selectFriendsList(username);
		List<UserVo> userVos = Lists.newArrayList();
		if(CollectionUtils.isNotEmpty(list)){
			for(Friends friends : list){
				UserVo userVo = assembleUserVo(friends, username);
				userVos.add(userVo);
			}
		}
		return ServerResponse.createBySuccess(userVos);
	}
	
	public ServerResponse applicationList(String username){
		List<FriendsApplication> list = friendsApplicationMapper.selectFriendsApplicationList(username);
		List<FriendsApplicationVo> applicationVos = Lists.newArrayList();
		int resultCount = friendsApplicationMapper.selectFriendsApplicationCount(username);
		if(CollectionUtils.isNotEmpty(list)){
			for(FriendsApplication friendsApplication : list){
				FriendsApplicationVo friendsApplicationVo = assembleFriendsApplicationVo(friendsApplication,resultCount);
				applicationVos.add(friendsApplicationVo);
			}
			return ServerResponse.createBySuccess(applicationVos);
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		
		return ServerResponse.createByErrorMessage(sdf.format(new Date()));
	}
	
	public ServerResponse agreeApplication(String username,String applicant){
		FriendsApplication friendsApplication = new FriendsApplication();
		friendsApplication.setApplicant(applicant);
		friendsApplication.setRespondent(username);
		friendsApplication.setState(1);
		
		Friends friends = new Friends();
		friends.setUsername(username);
		friends.setFriendname(applicant);
		
		int resultCount = friendsApplicationMapper.updateByPrimaryKeySelective(friendsApplication);
		if(resultCount > 0){
			resultCount = friendsMapper.insertSelective(friends);
			if(resultCount > 0){
				return ServerResponse.createBySuccessMessage("已添加");
			}
		}
		return ServerResponse.createByErrorMessage("添加失败");
	}
	
	public ServerResponse updateView(String respondent){
		int resultCount = friendsApplicationMapper.updateViewByRespondent(respondent);
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("修改成功");
		}
		return ServerResponse.createByErrorMessage("修改失败");
	}
	
	public ServerResponse setRemark(String username,String friendname,String remark){
		int resultCount = friendsMapper.checkFriend(username, friendname);
		if(resultCount > 0){
			Friends friends = new Friends();
			friends.setUsername(username);
			friends.setFriendname(friendname);
			friends.setRemark1(remark);
			resultCount = friendsMapper.updateByPrimaryKeySelective(friends);
			if(resultCount > 0){
				return ServerResponse.createBySuccessMessage("设置好友备注成功");
			}
		}else{
			Friends friends = new Friends();
			friends.setUsername(friendname);
			friends.setFriendname(username);
			friends.setRemark2(remark);
			resultCount = friendsMapper.updateByPrimaryKeySelective(friends);
			if(resultCount > 0){
				return ServerResponse.createBySuccessMessage("设置好友备注成功");
			}
		}
		
		return ServerResponse.createByErrorMessage("设置好友备注失败");
	}
	
	public ServerResponse deleteFriends(String username,String friendname){
		FriendsKey friendsKey = new FriendsKey();
		friendsKey.setUsername(username);
		friendsKey.setFriendname(friendname);
		
		FriendsApplicationKey friendsApplicationKey = new FriendsApplicationKey();
		
		int resultCount = friendsMapper.deleteByPrimaryKey(friendsKey);
		if(resultCount > 0){
			friendsApplicationKey.setApplicant(friendname);
			friendsApplicationKey.setRespondent(username);
			resultCount = friendsApplicationMapper.deleteByPrimaryKey(friendsApplicationKey);
			if(resultCount > 0){
				return ServerResponse.createBySuccessMessage("删除好友成功");
			}
		}else{
			friendsKey.setUsername(friendname);
			friendsKey.setFriendname(username);
			resultCount = friendsMapper.deleteByPrimaryKey(friendsKey);
			if(resultCount > 0){
				friendsApplicationKey.setApplicant(username);
				friendsApplicationKey.setRespondent(friendname);
				resultCount = friendsApplicationMapper.deleteByPrimaryKey(friendsApplicationKey);
				if(resultCount > 0){
					return ServerResponse.createBySuccessMessage("删除好友成功");
				}
			}
		}
		
		return ServerResponse.createByErrorMessage("参数错误");
	}
	
	public ServerResponse shareFile(FriendsShare friendsShare){
		Date date = new Date();
		friendsShare.setSharingTime(date);
		friendsShare.setIsview(0);
		int resultCount = friendsShareMapper.insertSelective(friendsShare);
		
		FriendsSession friendsSession = new FriendsSession();
		friendsSession.setUsername(friendsShare.getDistributors());
		friendsSession.setFriend(friendsShare.getReceiver());
		friendsSession.setNewSharingTime(date);
		friendsSession.setNewTitle(friendsShare.getTitle());
		friendsSession.setVisited1(1);
		friendsSession.setVisited2(1);
		
		if(resultCount > 0){
			resultCount = friendsSessionMapper.checkUserAndFriendExist(friendsShare.getDistributors(), friendsShare.getReceiver());
			if(resultCount > 0){
				resultCount = friendsSessionMapper.updateByUserAndFriend(friendsSession);
				if(resultCount > 0){
					return ServerResponse.createBySuccessMessage("分享文件成功");
				}
			}else{
				resultCount = friendsSessionMapper.insertSelective(friendsSession);
				if(resultCount > 0){
					return ServerResponse.createBySuccessMessage("分享文件成功");
				}
			}
			return ServerResponse.createBySuccessMessage("分享文件成功");
		}
		return ServerResponse.createByErrorMessage("分享文件失败");
	}
	
	public ServerResponse sessionList(String username){
		List<FriendsSession> list = friendsSessionMapper.selectFriendsSessionList(username);
		List<FriendsSessionVo> friendsSessionVos = Lists.newArrayList();
		for(FriendsSession friendsSession : list){
			FriendsSessionVo friendsSessionVo = assembleFriendsSessionVo(friendsSession,username);
			friendsSessionVos.add(friendsSessionVo);
		}
		return ServerResponse.createBySuccess(friendsSessionVos);
	}
	
	public ServerResponse deleteSessionList(Integer id,String username){
		FriendsSession friendsSession = friendsSessionMapper.selectByPrimaryKey(id);
		
		FriendsSession friendsSession2 = new FriendsSession();
		friendsSession2.setId(id);
		if(username.equals(friendsSession.getUsername())){
			friendsSession2.setVisited1(0);
		}else{
			friendsSession2.setVisited2(0);
		}
		
		int resultCount = friendsSessionMapper.updateByPrimaryKeySelective(friendsSession2);
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("删除成功");
		}
		return ServerResponse.createByErrorMessage("删除失败");
	}
	
	public ServerResponse<List<FriendsShareListVo>> getFriendsShareList(int id,User user){
		FriendsSession friendsSession = friendsSessionMapper.selectByPrimaryKey(id);
		List<FriendsShare> friendsShares = friendsShareMapper.selectFileIdGroup(friendsSession.getUsername(),friendsSession.getFriend());
		
		List<FriendsShareListVo> friendsShareListVos = Lists.newArrayList();
		for(FriendsShare friendsShare : friendsShares){
			friendsShareMapper.updateIsView(friendsShare.getId(),user.getUsername());
			
			FriendsShareListVo friendsShareListVo = assembleFriendsShareListVo(friendsShare,user);
			friendsShareListVos.add(friendsShareListVo);
		}
		return ServerResponse.createBySuccess(friendsShareListVos);
	}
	
	public ServerResponse deleteFriendsShareList(String valArr){
		String []str = valArr.split(",");
		
		Map<String, List<Integer>> map = Maps.newHashMap();
		List<Integer> list = Lists.newArrayList();
		
		for(int i = 0,len = str.length;i < len ; i++){
			list.add(Integer.parseInt(str[i].trim()));
		}
		
		map.put("id", list);
		
		int resultCount = friendsShareMapper.plDelete(map);
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("删除成功");
		}
		
		return ServerResponse.createByErrorMessage("删除失败");
	}
	
	public ServerResponse getFriendsCount(String username){
		int resultCount = friendsMapper.selectFriendsCount(username);
		return ServerResponse.createBySuccess(resultCount);
	}
	
	private FriendsApplicationVo assembleFriendsApplicationVo(FriendsApplication friendsApplication,Integer count){
		FriendsApplicationVo friendsApplicationVo = new FriendsApplicationVo();
		
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		
		friendsApplicationVo.setApplicant(friendsApplication.getApplicant());
		friendsApplicationVo.setDecode_applicant(UsernameEncryptionUtil.encryptionUsername(friendsApplication.getApplicant()));
		friendsApplicationVo.setRespondent(friendsApplication.getRespondent());
		friendsApplicationVo.setMessages(friendsApplication.getMessages());
		friendsApplicationVo.setCreatedtime(sdf.format(friendsApplication.getCreatedtime()));
		friendsApplicationVo.setState(friendsApplication.getState());
		friendsApplicationVo.setCount(count);
		
		return friendsApplicationVo;
	}
	
	private FriendsSessionVo assembleFriendsSessionVo(FriendsSession friendsSession,String username){
		FriendsSessionVo friendsSessionVo = new FriendsSessionVo();
		
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		
		if(friendsSession.getUsername().equals(username)){
			User user = userMapper.selectByPrimaryKey(friendsSession.getFriend());
			
			FriendsKey friendsKey = new FriendsKey(friendsSession.getUsername(),friendsSession.getFriend());
			Friends friends = friendsMapper.selectByPrimaryKey(friendsKey);
			
			if(friends.getUsername().equals(username)){
				if(friends.getRemark1() != null){
					friendsSessionVo.setShowInfo(friends.getRemark1());
				}else if(user.getNickname() != null){
					friendsSessionVo.setShowInfo(user.getNickname());
				}else{
					friendsSessionVo.setShowInfo(UsernameEncryptionUtil.encryptionUsername(friendsSession.getFriend()));
				}
			}else{
				if(friends.getRemark2() != null){
					friendsSessionVo.setShowInfo(friends.getRemark2());
				}else if(user.getNickname() != null){
					friendsSessionVo.setShowInfo(user.getNickname());
				}else{
					friendsSessionVo.setShowInfo(UsernameEncryptionUtil.encryptionUsername(friendsSession.getFriend()));
				}
			}
			
			int count = friendsShareMapper.selectCount(friendsSession.getFriend(), friendsSession.getUsername());
			
			friendsSessionVo.setCount(count);
			friendsSessionVo.setFriend(friendsSession.getFriend());
			friendsSessionVo.setUsername(friendsSession.getUsername());
		}else{
			User user = userMapper.selectByPrimaryKey(friendsSession.getUsername());
			
			FriendsKey friendsKey = new FriendsKey(friendsSession.getUsername(),friendsSession.getFriend());
			Friends friends = friendsMapper.selectByPrimaryKey(friendsKey);
			
			if(friends.getUsername().equals(username)){
				if(friends.getRemark1() != null){
					friendsSessionVo.setShowInfo(friends.getRemark1());
				}else if(user.getNickname() != null){
					friendsSessionVo.setShowInfo(user.getNickname());
				}else{
					friendsSessionVo.setShowInfo(UsernameEncryptionUtil.encryptionUsername(friendsSession.getUsername()));
				}
			}else{
				if(friends.getRemark2() != null){
					friendsSessionVo.setShowInfo(friends.getRemark2());
				}else if(user.getNickname() != null){
					friendsSessionVo.setShowInfo(user.getNickname());
				}else{
					friendsSessionVo.setShowInfo(UsernameEncryptionUtil.encryptionUsername(friendsSession.getUsername()));
				}
			}
			
			int count = friendsShareMapper.selectCount(friendsSession.getUsername(), friendsSession.getFriend());
			
			friendsSessionVo.setCount(count);
			friendsSessionVo.setFriend(friendsSession.getUsername());
			friendsSessionVo.setUsername(friendsSession.getFriend());
		}
		
		friendsSessionVo.setId(friendsSession.getId());
		friendsSessionVo.setNewSharingTime(sdf.format(friendsSession.getNewSharingTime()));
		friendsSessionVo.setNewTitle(friendsSession.getNewTitle());
		
		return friendsSessionVo;
	}
	
	private UserVo assembleUserVo(Friends friends,String username){
		UserVo userVo = new UserVo();
		
		
		if(username.equals(friends.getUsername())){
			userVo.setUsername(friends.getFriendname());
			userVo.setRemark(friends.getRemark1());
			userVo.setEncryptionName(UsernameEncryptionUtil.encryptionUsername(friends.getFriendname()));
		}else if(username.equals(friends.getFriendname())){
			userVo.setUsername(friends.getUsername());
			userVo.setRemark(friends.getRemark2());
			userVo.setEncryptionName(UsernameEncryptionUtil.encryptionUsername(friends.getUsername()));
		}
		
		if(friends.getUser().getNickname() == null || "".equals(friends.getUser().getNickname().trim())){
			userVo.setNickname("-");
		}else{
			userVo.setNickname(friends.getUser().getNickname());
		}
		
		return userVo;
	}
	
	private FriendsShareListVo assembleFriendsShareListVo(FriendsShare friendsShare,User user){
		FriendsShareListVo friendsShareListVo = new FriendsShareListVo();
		
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		String []imgTypes = {"jpg","jpeg","gif","png","bmp"};
		String []musicTypes = {"mp3","wav","wma","flac","ape","aac","ogg"};
		String []zipTypes = {"rar","zip","7z","iso","cab","arj","jar","rar5"};
		String []vedioTypes = {"avi","wmv","mpeg","mp4","mov","mkv","flv","f4v","m4v","rmvb",
				"rm","3gp","dat","ts","mts","vob"};
		
		
		friendsShareListVo.setId(friendsShare.getId());
		friendsShareListVo.setTitle(friendsShare.getTitle());
		friendsShareListVo.setSharingTime(sdf.format(friendsShare.getSharingTime()));
		friendsShareListVo.setTime(sdf1.format(friendsShare.getSharingTime()));
		friendsShareListVo.setFileIdGroup(friendsShare.getFileIdGroup());
		
		if(user.getUsername().equals(friendsShare.getDistributors())){
			if(user.getNickname() == null){
				friendsShareListVo.setDistributors(user.getUsername());
			}else{
				friendsShareListVo.setDistributors(user.getNickname());
			}
			friendsShareListVo.setIsDistributors(1);
		}else{
			friendsShareListVo.setIsDistributors(0);
			
			FriendsKey friendsKey = new FriendsKey(friendsShare.getDistributors(),friendsShare.getReceiver());
			Friends friends = friendsMapper.selectByPrimaryKey(friendsKey);
			
			user = userMapper.selectByPrimaryKey(friendsShare.getDistributors());
			
			if(friends.getUsername().equals(user.getUsername())){
				if(friends.getRemark2() != null){
					friendsShareListVo.setDistributors(friends.getRemark2());
				}else if(user.getNickname() != null){
					friendsShareListVo.setDistributors(user.getNickname());
				}else{
					friendsShareListVo.setDistributors(UsernameEncryptionUtil.encryptionUsername(user.getUsername()));
				}
			}else{
				if(friends.getRemark1() != null){
					friendsShareListVo.setDistributors(friends.getRemark1());
				}else if(user.getNickname() != null){
					friendsShareListVo.setDistributors(user.getNickname());
				}else{
					friendsShareListVo.setDistributors(UsernameEncryptionUtil.encryptionUsername(user.getUsername()));
				}
			}
		}
		
		String []str = friendsShare.getFileIdGroup().split(",");
		if(str.length > 1){
			friendsShareListVo.setIcon("/nebula/" + Const.MULTI_ICON);
			friendsShareListVo.setSize("-");
			friendsShareListVo.setIsMulti(1);
		}else{
			friendsShareListVo.setIsMulti(0);
			if(str[0].length() <= 11){
				friendsShareListVo.setIcon("/nebula/" + Const.FOLDER_ICON);
				friendsShareListVo.setSize("-");
			}else if(str[0].length() == 15){
				String title = friendsShare.getTitle();
				String lowercaseSuffix = title.substring(title.lastIndexOf(".") + 1).toLowerCase().trim();
				
				Files files = filesMapper.selectByPrimaryKey(Long.parseLong(str[0]));
				friendsShareListVo.setSize(FileUtil.byteCountToDisplaySize(files.getFileSize()));
				
				//图片
				for(String type : imgTypes){
					if(lowercaseSuffix.indexOf(type) > -1){
						friendsShareListVo.setIcon("/nebula/" + Const.IMG_ICON);
						break;
					}
				}
				
				//音乐
				for(String type : musicTypes){
					if(lowercaseSuffix.indexOf(type) > -1){
						friendsShareListVo.setIcon("/nebula/" + Const.MUSIC_ICON);
						break;
					}
				}
				
				//压缩文件
				for(String type : zipTypes){
					if(lowercaseSuffix.indexOf(type) > -1){
						friendsShareListVo.setIcon("/nebula/" + Const.ZIP_ICON);
						break;
					}
				}
				
				//视频文件
				for(String type : vedioTypes){
					if(lowercaseSuffix.indexOf(type) > -1){
						friendsShareListVo.setIcon("/nebula/" + Const.VEDIO_ICON);
						break;
					}
				}
				
				if(friendsShareListVo.getIcon() == null || friendsShareListVo.getIcon().equals("")){
					if("apk".equals(lowercaseSuffix)){
						friendsShareListVo.setIcon("/nebula/" + Const.APK_ICON);
					}
					else if("torrent".equals(lowercaseSuffix)){
						friendsShareListVo.setIcon("/nebula/" + Const.BT_ICON);
					}
					else if("pdf".equals(lowercaseSuffix)){
						friendsShareListVo.setIcon("/nebula/" + Const.PDF_ICON);
					}
					else if("xls".equals(lowercaseSuffix)){
						friendsShareListVo.setIcon("/nebula/" + Const.XLS_ICON);
					}
					else if("txt".equals(lowercaseSuffix)){
						friendsShareListVo.setIcon("/nebula/" + Const.TXT_ICON);
					}
					else if("exe".equals(lowercaseSuffix)){
						friendsShareListVo.setIcon("/nebula/" + Const.EXE_ICON);
					}
					else if("folder".equals(lowercaseSuffix)){
						friendsShareListVo.setIcon("/nebula/" + Const.FOLDER_ICON);
					}
					else if("doc".equals(lowercaseSuffix) || "docx".equals(lowercaseSuffix)){
						friendsShareListVo.setIcon("/nebula/" + Const.DOC_ICON);
					}
					else if("ppt".equals(lowercaseSuffix) || "pptx".equals(lowercaseSuffix)){
						friendsShareListVo.setIcon("/nebula/" + Const.PPT_ICON);
					}
					else if("vsd".equals(lowercaseSuffix)){
						friendsShareListVo.setIcon("/nebula/" + Const.VSD_ICON);
					}
					else if("html".equals(lowercaseSuffix)){
						friendsShareListVo.setIcon("/nebula/" + Const.HTML_ICON);
					}
					else {
						friendsShareListVo.setIcon("/nebula/" + Const.UNKNOWN_ICON);
					}
				}
			}
		}
		
		return friendsShareListVo;
	}
}
